package com.rpc.learn.consume;

import com.rpc.learn.regist.LocalFileServiceRegister;
import com.rpc.learn.regist.ServiceRegister;
import com.rpc.learn.regist.ZkServiceRegister;
import com.rpc.learn.transport.NettyRpcClient;
import com.rpc.learn.transport.dto.RpcResponse;
import com.rpc.learn.transport.support.ServiceNameSupport;

import java.net.InetSocketAddress;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ServiceConsumer {

    private static ServiceRegister serviceRegister;
    private static NettyRpcClient nettyRpcClient = NettyRpcClient.getNettyRpcClient();

    static {
        //可在配置文件中配置使用哪种注册中心
        serviceRegister = new ZkServiceRegister();
    }

    public static Object invoke(String serviceName, Object ...params) {
        InetSocketAddress address = serviceRegister.lookup(ServiceNameSupport.getInstantName(serviceName));
        //发送参数，调用服务
        CompletableFuture<RpcResponse> result = nettyRpcClient.sendRequest(address, serviceName, params);
        try {
            return result.get(15, TimeUnit.SECONDS).getData();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        } catch (TimeoutException e) {
            e.printStackTrace();
            return null;
        } catch (ExecutionException e) {
            e.printStackTrace();
            return null;
        }
    }
}
